# -*- encoding: utf-8 -*-
##############################################################################
#
#    OpenERP, Open Source Management Solution
#    Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). All Rights Reserved
#    $Id$
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################

from osv import osv
import netsvc
import pooler
from mx import DateTime
import time

logger = netsvc.Logger()

class mrp_procurement(osv.osv):
    _inherit = 'mrp.procurement'

    def _procure_confirm(self, cr, uid, ids=None, use_new_cursor=False, context=None):
        '''
        use_new_cursor: False or the dbname
        '''
        if not context:
            context = {}

        if use_new_cursor:
            cr = pooler.get_db(use_new_cursor).cursor()
        wf_service = netsvc.LocalService("workflow")

        procurement_obj = self.pool.get('mrp.procurement')
        if not ids:
            ids = procurement_obj.search(cr, uid, [], order="date_planned")
        for id in ids:
            wf_service.trg_validate(uid, 'mrp.procurement', id, 'button_restart', cr)
        if use_new_cursor:
            cr.commit()

        company = self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id
        maxdate = DateTime.now() + DateTime.RelativeDateTime(days=company.schedule_range)
        start_date = time.strftime('%Y-%m-%d, %Hh %Mm %Ss')
        offset = 0
        report = []
        report_total = 0
        report_except = 0
        report_later = 0
        while True:
            cr.execute('select id from mrp_procurement where state=%s and procure_method=%s order by date_planned limit 500 offset %s', ('confirmed', 'make_to_order', offset))
            ids = map(lambda x: x[0], cr.fetchall())
            for proc in procurement_obj.browse(cr, uid, ids):
                if (maxdate.strftime('%Y-%m-%d')>=proc.date_planned):
                    wf_service.trg_validate(uid, 'mrp.procurement', proc.id, 'button_check', cr)
                else:
                    offset += 1
                    report_later += 1
            for proc in procurement_obj.browse(cr, uid, ids):
                if proc.state == 'exception':
                    report.append('PROC %d: on order - %3.2f %-5s - %s' % \
                            (proc.id, proc.product_qty, proc.product_uom.name,
                                proc.product_id.name))
                    report_except += 1
                report_total += 1
            if use_new_cursor:
                cr.commit()
            if not ids:
                break

        offset = 0
        ids = []
        while True:
            report_ids = []
            ids = self.pool.get('mrp.procurement').search(cr, uid, [('state', '=', 'confirmed'), ('procure_method', '=', 'make_to_stock')], order="date_planned",offset=offset)
            for proc in procurement_obj.browse(cr, uid, ids):
                if ((maxdate).strftime('%Y-%m-%d') >= proc.date_planned) :
                    wf_service.trg_validate(uid, 'mrp.procurement', proc.id, 'button_check', cr)
                    report_ids.append(proc.id)
                else:
                    report_later += 1
                report_total += 1
            for proc in procurement_obj.browse(cr, uid, report_ids):
                if proc.state == 'exception':
                    report.append('PROC %d: from stock - %3.2f %-5s - %s' % \
                            (proc.id, proc.product_qty, proc.product_uom.name,
                                proc.product_id.name,))
                    report_except += 1
            if use_new_cursor:
                cr.commit()
            offset += len(ids)
            if not ids: break
        end_date = time.strftime('%Y-%m-%d, %Hh %Mm %Ss')
        if uid:
            request = self.pool.get('res.request')
            summary = '''Here is the procurement scheduling report.

    Computation Started; %s
    Computation Finished; %s

    Total procurement: %d
    Exception procurement: %d
    Not run now procurement: %d

    Exceptions;
    '''% (start_date, end_date, report_total, report_except, report_later)
            summary += '\n'.join(report)
            request.create(cr, uid,
                {'name': "Procurement calculation report.",
                    'act_from': uid,
                    'act_to': uid,
                    'body': summary,
                })
        if use_new_cursor:
            cr.commit()
            cr.close()
        return {}

    def create_automatic_op(self, cr, uid, context=None):
        if not context:
            context = {}
        product_obj = self.pool.get('product.product')
        proc_obj = self.pool.get('mrp.procurement')
        warehouse_obj = self.pool.get('stock.warehouse')
        wf_service = netsvc.LocalService("workflow")

        warehouse_ids = warehouse_obj.search(cr, uid, [], context=context)

        cr.execute('select id from product_product')
        products_id = [x for x, in cr.fetchall()]

        for warehouse in warehouse_obj.browse(cr, uid, warehouse_ids, context=context):
            context['warehouse'] = warehouse
            for product in self.pool.get('product.product').browse(cr, uid, products_id, context=context):
                if product.virtual_available >= 0.0:
                    continue

                newdate = DateTime.now()
                if product.supply_method == 'buy':
                    location_id = warehouse.lot_input_id.id
                elif product.supply_method == 'produce':
                    location_id = warehouse.lot_stock_id.id
                else:
                    continue
                proc_id = proc_obj.create(cr, uid, {
                    'name': 'Automatic OP: %s' % product.name,
                    'origin': 'SCHEDULER',
                    'date_planned': newdate.strftime('%Y-%m-%d %H:%M:%S'),
                    'product_id': product.id,
                    'product_qty': -product.virtual_available,
                    'product_uom': product.uom_id.id,
                    'location_id': location_id,
                    'procure_method': 'make_to_order',
                    })
                wf_service.trg_validate(uid, 'mrp.procurement', proc_id, 'button_confirm', cr)
                wf_service.trg_validate(uid, 'mrp.procurement', proc_id, 'button_check', cr)

        #added by amgad 24-10-2010
    def _get_max_Procurment_date(self,cr,uid,product_id,parent_prod_qty,context,virtual_prods_amount={}):
         if not context:
            context = {}
         orderpoint_obj = self.pool.get('stock.warehouse.orderpoint')
         location_obj = self.pool.get('stock.location')
         mrp_bom_obj = self.pool.get('mrp.bom')
         #logger.notifyChannel('init', netsvc.LOG_WARNING, '11: ')
         #logger.notifyChannel('init', netsvc.LOG_WARNING, 'product_id: %s , qty: %s' %(product_id,parent_prod_qty))
         logger.notifyChannel('_get_max_Procurment_date', netsvc.LOG_WARNING, ' starting _get_max_Procurment_date')    
         sids_bom = self.pool.get('mrp.bom').search(cr, uid, [('bom_id','=',False),('product_id','=',product_id)])
         if sids_bom:
            logger.notifyChannel('_get_max_Procurment_date', netsvc.LOG_WARNING, ' sids_bom found')
            bom = self.pool.get('mrp.bom').browse(cr, uid, sids_bom[0], context=context)
            max_bom_seller_delay = 0
            for line in bom.bom_lines:
                line_id = orderpoint_obj.search(cr, uid, [('product_id','=',line.product_id.id)], offset=0, limit=100)
                line_op = orderpoint_obj.browse(cr, uid, line_id[0])
                #added by amgad 30-11-2010
                #cause adding virtual_prods_amount support
                if virtual_prods_amount.has_key(line.product_id.id):
                    logger.notifyChannel('_get_max_Procurment_date', netsvc.LOG_WARNING, ' product id %s value already exist in map' %(line.product_id.id))
                    prods = virtual_prods_amount[line.product_id.id]
                else:    
                    logger.notifyChannel('_get_max_Procurment_date', netsvc.LOG_WARNING, ' product id %s value was not exist in map' %(line.product_id.id))
                    prods = location_obj._product_virtual_get(cr, uid,
                    line_op.location_id.id, [line_op.product_id.id],
                    {'uom': line_op.product_uom.id})[line_op.product_id.id]
                logger.notifyChannel('_get_max_Procurment_date', netsvc.LOG_WARNING, ' product id %s value is from map' %(prods))
                
                needed_qty = parent_prod_qty * line.product_qty
                prods =  prods  - needed_qty 
                if prods < line_op.product_min_qty:
                    logger.notifyChannel('_get_max_Procurment_date', netsvc.LOG_WARNING, ' needed quantity %s less than min' %(prods))
                    
                #added by amgad 30-11-2010
                #cause adding virtual_prods_amount support
                    qty = max(line_op.product_min_qty, line_op.product_max_qty)-prods
                    reste = qty % line_op.qty_multiple
                    if reste > 0:
                        qty += line_op.qty_multiple - reste
                    logger.notifyChannel('_get_max_Procurment_date', netsvc.LOG_WARNING, ' adding new qty %s value to map' %(qty - needed_qty))    
                    virtual_prods_amount[line.product_id.id] = qty - needed_qty   
                        
                    if line_op.product_id.supply_method == 'produce':
                       logger.notifyChannel('_get_max_Procurment_date', netsvc.LOG_WARNING, ' is produce')
                       bom_line_seller_lead =  self._get_max_Procurment_date(cr,uid,line_op.product_id.id,needed_qty,context,virtual_prods_amount = virtual_prods_amount)
                       bom_line_seller_lead = bom_line_seller_lead + line_op.product_id.produce_delay
                    else:    
                        logger.notifyChannel('_get_max_Procurment_date', netsvc.LOG_WARNING, ' is not produce')
                        bom_line_seller_lead = int(line_op.product_id.seller_delay)
                    if bom_line_seller_lead > max_bom_seller_delay:
                        max_bom_seller_delay = bom_line_seller_lead   
            logger.notifyChannel('_get_max_Procurment_date', netsvc.LOG_WARNING, ' returned max_bom_seller_delay is %s' %(max_bom_seller_delay))                   
            return max_bom_seller_delay
         #added by amgad 24-10-2010        
        



    def _procure_orderpoint_confirm(self, cr, uid, automatic=False,\
            use_new_cursor=False, context=None, user_id=False):
        '''
        use_new_cursor: False or the dbname
        '''
        if not context:
            context = {}
        if use_new_cursor:
            cr = pooler.get_db(use_new_cursor).cursor()
        orderpoint_obj = self.pool.get('stock.warehouse.orderpoint')
        location_obj = self.pool.get('stock.location')
        procurement_obj = self.pool.get('mrp.procurement')
        mrp_bom_obj = self.pool.get('mrp.bom')
        request_obj = self.pool.get('res.request')
        purchase_obj = self.pool.get('purchase.order')
        uom_obj = self.pool.get('product.uom')
        wf_service = netsvc.LocalService("workflow")
        report = []
        offset = 0
        ids = [1]
        if automatic:
            self.create_automatic_op(cr, uid, context=context)
        #added by amgad 27-10-2010
        logger.notifyChannel('_procure_orderpoint_confirm', netsvc.LOG_WARNING, 'starting  _procure_orderpoint_confirm method')
        production_order_made = False
        production_obj = self.pool.get('mrp.production')    
        logger.notifyChannel('_procure_orderpoint_confirm', netsvc.LOG_WARNING, 'getting production_ids')
        production_ids = production_obj.search(cr, uid, [])
        #added by Amgad Alaa 10-4-2011
        #Cause: calculating to be purchased amounts
        ################################
        purchase_ids = purchase_obj.search(cr, uid, [('state','in',('draft','confirmed'))],)
        toPurchaseProductsAmount={}
        for purchaseOrders in purchase_obj.browse(cr, uid,purchase_ids):
            for purchaseLines in purchaseOrders.order_line:
                existingAmount = 0
                if toPurchaseProductsAmount.has_key(purchaseLines.product_id.id):
                    existingAmount = toPurchaseProductsAmount[purchaseLines.product_id.id] 
                amountInLineUOMQTY = uom_obj._compute_qty(cr, uid, purchaseLines.product_uom.id, purchaseLines.product_qty, purchaseLines.product_id.uom_id.id)
                existingAmount = existingAmount + amountInLineUOMQTY
                toPurchaseProductsAmount[purchaseLines.product_id.id] = existingAmount                
        ################################    
        
        #added by amgad 27-10-2010
        while ids:
            #added by amgad 25-12-2010
            #cause: order by name so that procurements are made in order and affects each other
            #so that in one mrp run all procurements are made for all levels 
            ids = orderpoint_obj.search(cr, uid, [], offset=offset, order="name",limit=100)
            logger.notifyChannel('_procure_orderpoint_confirm', netsvc.LOG_WARNING, 'looping on order points(op)')
            for op in orderpoint_obj.browse(cr, uid, ids):
                 #commented by Amgad Alaa 10-4-2011
                 #Cause:so that mps can be done even there are still not done production orders or purchase orders
#                #skip for to be purchased products in case purchase order already created
#                if op.procurement_id and op.procurement_id.purchase_id and op.procurement_id.purchase_id.state in ('draft', 'confirmed'):
#                    continue
#                #added by amgad 27-10-2010
#                #skip for to be produced products in case production order already created
#                #########################################
#                for production_orders in production_obj.browse(cr, uid, production_ids):
#                    if production_orders.origin ==  op.name and production_orders.state not in ('done'):
#                        production_order_made = True
#                        break
#                if production_order_made == True:
#                    continue
#                
#                prods = location_obj._product_virtual_get(cr, uid,
#                        op.location_id.id, [op.product_id.id],
#                        {'uom': op.product_uom.id})[op.product_id.id]
#                if prods < op.product_min_qty:
#                    qty = max(op.product_min_qty, op.product_max_qty)-prods
#                    reste = qty % op.qty_multiple
#                    if reste > 0:
#                        qty += op.qty_multiple - reste
#                #########################################
#                    newdate = DateTime.now() + DateTime.RelativeDateTime(
#                            days=int(op.product_id.seller_delay))
#                    if op.product_id.supply_method == 'buy':
#                        location_id = op.warehouse_id.lot_input_id
#                    elif op.product_id.supply_method == 'produce':
#                        location_id = op.warehouse_id.lot_stock_id
                        #=======================================================
                        # #added by amgad 23-10-2010
                        # sids_bom = self.pool.get('mrp.bom').search(cr, uid, [('bom_id','=',False),('product_id','=',op.product_id.id)])
                        # if sids_bom:
                        #    bom = self.pool.get('mrp.bom').browse(cr, uid, sids_bom[0], context=context)
                        #    max_bom_seller_delay = 0
                        #    for line in bom.bom_lines:
                        #        line_id = orderpoint_obj.search(cr, uid, [('product_id','=',line.product_id.id)], offset=offset, limit=100)
                        #        line_op = orderpoint_obj.browse(cr, uid, line_id[0])
                        #        prods = location_obj._product_virtual_get(cr, uid,
                        #        line_op.location_id.id, [line_op.product_id.id],
                        #        {'uom': line_op.product_uom.id})[line_op.product_id.id]
                        #        prods =  prods  - ( qty * line.product_qty )
                        #        if prods < line_op.product_min_qty:
                        #            bom_line_seller_lead = int(line_op.product_id.seller_delay)
                        #            if bom_line_seller_lead > max_bom_seller_delay:
                        #                max_bom_seller_delay = bom_line_seller_lead 
                        #    newdate = newdate + DateTime.RelativeDateTime(
                        #    days=int(max_bom_seller_delay))     
                        # #added by amgad 23-10-2010           
                        #=======================================================
#                    else:
#                        continue
                    if op.product_id.supply_method not in ('buy','produce'):
                        continue
                    #added by amgad 20-11-2010
                    #cause: modifying behaviour to process many MPS of differnet months  
                    #also ('state','not in',('done','cancel')) added by Amgad Alaa 24-4-2011
                    logger.notifyChannel('_procure_orderpoint_confirm', netsvc.LOG_WARNING, 'starting mps handling')
                    from_mps_procs_ids = self.pool.get('mrp.procurement').search(cr, uid, [('is_mps','=',True),('mps_handling_done','<>',True),('product_id','=',op.product_id.id),
                                                                                          ('state','not in',('done','cancel')),('procure_method', '=', 'make_to_stock')],order="date_planned")
                    if from_mps_procs_ids:
                                        
                        #added by Amgad Alaa 10-4-2011
                        #Cause:so that mps can be done even there are still not done production orders or purchase orders
                        #################################
                        prods = location_obj._product_virtual_get(cr, uid,
                                op.location_id.id, [op.product_id.id],
                                {'uom': op.product_uom.id})[op.product_id.id]    
                        if op.product_id.supply_method == 'buy':      
                            if toPurchaseProductsAmount.has_key(op.product_id.id):
                                qtyInOPUOM = uom_obj._compute_qty(cr, uid, op.product_id.uom_id.id, toPurchaseProductsAmount[op.product_id.id], op.product_uom.id)
                                prods = prods + qtyInOPUOM
     
                                
                        logger.notifyChannel('_procure_orderpoint_confirm', netsvc.LOG_WARNING, 'mps found for product ID:%s' %(op.product_id.id))
                        from_mps_procs = self.pool.get('mrp.procurement').browse(cr, uid,from_mps_procs_ids , context=context)  
                        is_mps_base_record = from_mps_procs[0].is_mps_base_record or False
                        #added b Amgad Alaa 24-4-2011
                        #dummy initialization
                        qty = 0
                        if prods < op.product_min_qty:
                            qty = max(op.product_min_qty, op.product_max_qty)-prods
                            reste = qty % op.qty_multiple
                            if reste > 0:
                                qty += op.qty_multiple - reste
                        if qty <= 0 and not is_mps_base_record:
                            continue
                        ######################################   
                        total_mps_qty = 0
                        #get total MPS qty
                        for each_mps_proc in from_mps_procs:
                            qtyInOPUOM = uom_obj._compute_qty(cr, uid, each_mps_proc.product_uom.id, each_mps_proc.product_qty, op.product_uom.id)
                            total_mps_qty += qtyInOPUOM
                        logger.notifyChannel('_procure_orderpoint_confirm', netsvc.LOG_WARNING, 'total mps amount:%s' %(total_mps_qty))    
                        mps_period_product_qty = prods + total_mps_qty
                        logger.notifyChannel('_procure_orderpoint_confirm', netsvc.LOG_WARNING, 'first period product stock amount:%s' %(mps_period_product_qty))
                        #added by amgad 1/12/2010
                        #map that is used to contain the latest virtual products amount
                        virtual_prods_amount={}
                        #used when the MPS records are form stock planning module
                        firstTimeMPS = True
                        for each_mps_proc in from_mps_procs:        
                            if each_mps_proc.state in ('cancel','done'):
                                 continue 
                             
                            eachMPSProductQtyInOPUOM = uom_obj._compute_qty(cr, uid, each_mps_proc.product_uom.id, each_mps_proc.product_qty, op.product_uom.id)
                            if op.product_id.type not in ('consu'):
                                
                                # Added by Amgad Alaa 23-7-2011
                                # Cause: fixing MPS issue related to MPS location
                                mps_identity = each_mps_proc.mps_identity
                                if is_mps_base_record:
                                    if firstTimeMPS:
                                        firstTimeMPS = False
                                        if prods < op.product_min_qty:
                                            to_add_qty_to_first_MPS = max(op.product_min_qty, op.product_max_qty)-prods
                                            mps_period_needed_qty = eachMPSProductQtyInOPUOM + to_add_qty_to_first_MPS
                                        else:
                                            mps_period_needed_qty = eachMPSProductQtyInOPUOM 
                                    else:
                                        mps_period_needed_qty = eachMPSProductQtyInOPUOM
                                    
                                    reste = mps_period_needed_qty % op.qty_multiple
                                    if reste > 0:
                                        mps_period_needed_qty += op.qty_multiple - reste
                                else:    
                                ###############################################
                                    mps_period_needed_qty = 0
                                    logger.notifyChannel('_procure_orderpoint_confirm', netsvc.LOG_WARNING, 'mps name:%s ,found, date:%s' %(each_mps_proc.name,each_mps_proc.date_planned))
                                    mps_period_product_qty = mps_period_product_qty - eachMPSProductQtyInOPUOM
                                    logger.notifyChannel('_procure_orderpoint_confirm', netsvc.LOG_WARNING, 'product stock amount after mps:%s' %(mps_period_product_qty))
                                    if mps_period_product_qty < op.product_min_qty:
                                        logger.notifyChannel('_procure_orderpoint_confirm', netsvc.LOG_WARNING, 'min stock level violated:%s' %(mps_period_product_qty))
                                        mps_period_needed_qty = max(op.product_min_qty, op.product_max_qty)-mps_period_product_qty
                                        reste = mps_period_needed_qty % op.qty_multiple
                                        if reste > 0:
                                            mps_period_needed_qty += op.qty_multiple - reste   
                                        logger.notifyChannel('_procure_orderpoint_confirm', netsvc.LOG_WARNING, 'to procure quantity:%s' %(mps_period_needed_qty))    
                                        mps_period_product_qty = mps_period_product_qty +  mps_period_needed_qty 
                                        logger.notifyChannel('_procure_orderpoint_confirm', netsvc.LOG_WARNING, 'product stock after mps:%s' %(mps_period_product_qty))    
                                    if mps_period_needed_qty <= 0:
                                        continue    
                                #newdate = each_mps_proc.date_planned + DateTime.RelativeDateTime(
                                #days=int(op.product_id.seller_delay))
                                newdate = DateTime.Date(int(each_mps_proc.mps_base_date[0:4]),int(each_mps_proc.mps_base_date[5:7]),
                                                        int(each_mps_proc.mps_base_date[8:10]))
                                mps_base_date = newdate 
#                                newdate = DateTime.Date(int(each_mps_proc.mps_base_date[0:4]),int(each_mps_proc.mps_base_date[5:7]),
#                                                        int(each_mps_proc.mps_base_date[8:10]))+ DateTime.RelativeDateTime(
#                                                        days=int(op.product_id.seller_delay))
#                                logger.notifyChannel('_procure_orderpoint_confirm', netsvc.LOG_WARNING, 'mps date base:%s' %(each_mps_proc.mps_base_date))
#                                logger.notifyChannel('_procure_orderpoint_confirm', netsvc.LOG_WARNING, 'date base:%s' %(newdate))
                                if op.product_id.supply_method == 'buy':
                                    location_id = op.warehouse_id.lot_input_id
                                elif op.product_id.supply_method == 'produce':
                                    mps_base_date = mps_base_date - DateTime.RelativeDateTime(days=int(op.product_id.produce_delay))
                                    location_id = op.warehouse_id.lot_stock_id
#                                    logger.notifyChannel('_procure_orderpoint_confirm', netsvc.LOG_WARNING, 'calling _get_max_Procurment_date')
#                                    logger.notifyChannel('_procure_orderpoint_confirm', netsvc.LOG_WARNING, 'virtual_prods_amount Values are : %s' %  virtual_prods_amount.items())
#                                    max_bom_seller_delay = self._get_max_Procurment_date(cr,uid,op.product_id.id,mps_period_needed_qty,context,virtual_prods_amount = virtual_prods_amount)
#                                    if max_bom_seller_delay:
#                                        logger.notifyChannel('_procure_orderpoint_confirm', netsvc.LOG_WARNING, 'max_bom_seller_delay is:%s' %(max_bom_seller_delay))
#                                        newdate = newdate + DateTime.RelativeDateTime(
#                                        days=int(max_bom_seller_delay)) + DateTime.RelativeDateTime(days=int(op.product_id.produce_delay))
#                                    else:
#                                        newdate = newdate +  DateTime.RelativeDateTime(days=int(op.product_id.produce_delay))         
                                logger.notifyChannel('_procure_orderpoint_confirm', netsvc.LOG_WARNING, 'final planned date is:%s' %(newdate))    
                                proc_id = procurement_obj.create(cr, uid, {
                                'name': 'OP:' + str(op.id)+mps_identity,
                                'date_planned': newdate.strftime('%Y-%m-%d'),
                                'product_id': op.product_id.id,
                                'product_qty': mps_period_needed_qty,
                                'product_uom': op.product_uom.id,
                                'location_id': op.warehouse_id.lot_input_id.id,
                                'procure_method': 'make_to_order',
                                'origin': op.name,
                                'is_mps': True,
                                'mps_base_date':mps_base_date,
                                'mps_handling_done': True,
                                'mps_identity':mps_identity,
                                'supply_method': op.product_id.supply_method,
                                #'mps_base_date':each_mps_proc.mps_base_date,
                                })
                                wf_service.trg_validate(uid, 'mrp.procurement', proc_id,
                                        'button_confirm', cr)
                                wf_service.trg_validate(uid, 'mrp.procurement', proc_id,
                                        'button_check', cr)
                                orderpoint_obj.write(cr, uid, [op.id],
                                        {'procurement_id': proc_id}) 
                        logger.notifyChannel('_procure_orderpoint_confirm', netsvc.LOG_WARNING, 'mark  mps as handled')       
                        #mark all handled MPS as done                
                        #procurement_obj.write(cr, uid, from_mps_procs_ids, {'mps_handling_done': True})      
                        procurement_obj.write(cr, uid, [x for x in from_mps_procs_ids], {'mps_handling_done': True})      
                    #normal make to stock in case no MPS            
                    else:
                        
                        logger.notifyChannel('_procure_orderpoint_confirm', netsvc.LOG_WARNING, 'no mps found for product ID:%s' %(op.product_id.id))
                        #moved to here by Amgad Alaa 10-4-2011
                        #Cause:so that mps can be done even there are still not done production orders or purchase orders
                        #skip for to be purchased products in case purchase order already created
                        if op.procurement_id and op.procurement_id.purchase_id and op.procurement_id.purchase_id.state in ('draft', 'confirmed') and op.product_id.supply_method == 'buy':
                            logger.notifyChannel('_procure_orderpoint_confirm', netsvc.LOG_WARNING, 'op number: %s, will continue' %(op.id))
                            continue
                        #added by amgad 27-10-2010
                        #skip for to be produced products in case production order already created
                        #########################################
                        production_order_made = False
                        for production_orders in production_obj.browse(cr, uid, production_ids):
                            if production_orders.origin ==  op.name and production_orders.state not in ('done' ,'cancel'):
                                production_order_made = True
                                logger.notifyChannel('_procure_orderpoint_confirm', netsvc.LOG_WARNING, 'production number: %s, not done yet' %(production_orders.id))
                                break
                        if production_order_made == True:
                            continue
                        
                                        
                        prods = location_obj._product_virtual_get(cr, uid,
                                op.location_id.id, [op.product_id.id],
                                {'uom': op.product_uom.id})[op.product_id.id]
                                
                        #Added by Amgad Alaa 26-8-2011
                        #Cause: calculating to be purchased amounts
                        if op.product_id.supply_method == 'buy':      
                            if toPurchaseProductsAmount.has_key(op.product_id.id):
                                qtyInOPUOM = uom_obj._compute_qty(cr, uid, op.product_id.uom_id.id, toPurchaseProductsAmount[op.product_id.id], op.product_uom.id)
                                prods = prods + qtyInOPUOM
                        #############################################
                        
                        #added b Amgad Alaa 28-4-2011
                        #dummy initialization
                        qty = 0
                        if prods < op.product_min_qty:
                            qty = max(op.product_min_qty, op.product_max_qty)-prods
                            reste = qty % op.qty_multiple
                            if reste > 0:
                                qty += op.qty_multiple - reste
                        if qty <= 0:
                            continue
                        #########################################
                       
                        if op.product_id.type not in ('consu'):
                            newdate = DateTime.now() + DateTime.RelativeDateTime(
                            days=int(op.product_id.seller_delay))
                            if op.product_id.supply_method == 'buy':
                                location_id = op.warehouse_id.lot_input_id
                            elif op.product_id.supply_method == 'produce':
                                location_id = op.warehouse_id.lot_stock_id
                                max_bom_seller_delay = self._get_max_Procurment_date(cr,uid,op.product_id.id,qty,context)
                                if max_bom_seller_delay:
                                    newdate = newdate + DateTime.RelativeDateTime(
                                    days=int(max_bom_seller_delay)) + DateTime.RelativeDateTime(days=int(op.product_id.produce_delay))
                                else:
                                    newdate = newdate +  DateTime.RelativeDateTime(days=int(op.product_id.produce_delay)) 
                            proc_id = procurement_obj.create(cr, uid, {
                                'name': 'OP:' + str(op.id),
                                'date_planned': newdate.strftime('%Y-%m-%d'),
                                'product_id': op.product_id.id,
                                'product_qty': qty,
                                'product_uom': op.product_uom.id,
                                'location_id': op.warehouse_id.lot_input_id.id,
                                'procure_method': 'make_to_order',
                                'origin': op.name,
                                'supply_method': op.product_id.supply_method,
                            })
                            wf_service.trg_validate(uid, 'mrp.procurement', proc_id,
                                    'button_confirm', cr)
                            wf_service.trg_validate(uid, 'mrp.procurement', proc_id,
                                    'button_check', cr)
                            orderpoint_obj.write(cr, uid, [op.id],
                                    {'procurement_id': proc_id})
                                


#commented by amgad 20-11-2010
#cause: modifying behaviour to process many MPS of differnet months                     
#                    if qty <= 0:
#                        continue
#                    if op.product_id.type not in ('consu'):
#                        proc_id = procurement_obj.create(cr, uid, {
#                            'name': 'OP:' + str(op.id),
#                            'date_planned': newdate.strftime('%Y-%m-%d'),
#                            'product_id': op.product_id.id,
#                            'product_qty': qty,
#                            'product_uom': op.product_uom.id,
#                            'location_id': op.warehouse_id.lot_input_id.id,
#                            'procure_method': 'make_to_order',
#                            'origin': op.name
#                        })
#                        wf_service.trg_validate(uid, 'mrp.procurement', proc_id,
#                                'button_confirm', cr)
#                        wf_service.trg_validate(uid, 'mrp.procurement', proc_id,
#                                'button_check', cr)
#                        orderpoint_obj.write(cr, uid, [op.id],
#                                {'procurement_id': proc_id})
            offset += len(ids)
            if use_new_cursor:
                cr.commit()
        if user_id and report:
            request_obj.create(cr, uid, {
                'name': 'Orderpoint report.',
                'act_from': user_id,
                'act_to': user_id,
                'body': '\n'.join(report)
                })
        if use_new_cursor:
            cr.commit()
            cr.close()
        return {}
mrp_procurement()
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
